package com.moon.filter;

import cn.hutool.http.server.HttpServerResponse;
import com.moon.utils.CurrentUserContextHolder;
import com.moon.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("初始化过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("开始执行过滤器");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        if (url.contains("/login")) {
            log.info("登录请求");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String token = request.getHeader("Token");
        if (!StringUtils.hasLength(token)) {
            log.info("没有token");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        try {
            Claims claims = JwtUtils.parseJWT(token);
            CurrentUserContextHolder.set(JwtUtils.getLoginInfoFromToken(claims));
        } catch (Exception e) {
            log.info("token解析失败");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);

        CurrentUserContextHolder.clear();
    }

    @Override
    public void destroy() {
        log.info("销毁过滤器");
    }
}
